package com.easy.project.util;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.easy.project.base.exception.ServiceException;
import com.easy.project.base.result.SystemErrorCodeEnum;
import lombok.Builder;
import lombok.Data;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 鉴权工具类
 */
@Component
public class SaTokenUtils {

    // 公钥的map key
    private static final String PUBLIC_MAP_KEY = "public";

    // 私钥的 map key
    private static final String PRIVATE_MAP_KEY = "private";

    // 是否为管理员账号的key
    public static final String IS_ADMIN = "isAdmin";



    /**
     * 判断是否为admin用户
     * @return
     */
    public static boolean isAdmin(){
        return (Boolean) StpUtil.getExtra(IS_ADMIN);
    }

    /**
     * 根据身份证号码生成 密码 规则：身份证后六位
     *
     * @param idNumber
     * @return
     */
    public static String generateIdNumberPassword(String idNumber) {
        String password = idNumber.substring(idNumber.length() - 6);
        return SaSecureUtil.md5(password);
    }

    /**
     * 生成加密的密码
     *
     * @param password
     * @return
     */
    public static String generatePassword(String password) {
        return SaSecureUtil.md5(password);
    }

    /**
     * 解密password
     *
     * @param password   公钥加密后的密码
     * @param privateKey 私钥
     * @return
     */
    public static String decryptRsaPassword(String password, String privateKey) {
        return SaSecureUtil.rsaDecryptByPrivate(privateKey,password);
    }

    /**
     * 生成RsaKey
     *
     * @return
     */
    public static RsaKey generateRsaKey() {
        HashMap<String, String> keyMap;
        try {
            keyMap = SaSecureUtil.rsaGenerateKeyPair();
        } catch (Exception e) {
            throw new ServiceException(SystemErrorCodeEnum.ERROR_INFO, "生成rsa失败!");
        }
        String publicKey = keyMap.get(PUBLIC_MAP_KEY);
        String privateKey = keyMap.get(PRIVATE_MAP_KEY);
        return RsaKey.builder()
                .privateKey(privateKey)
                .publicKey(publicKey)
                .build();
    }

    @Data
    @Builder
    public static class RsaKey {

        // 公钥
        private String publicKey;

        // 私钥
        private String privateKey;

    }
}
